<template>
    <div>
        <el-container>
            <el-header class="inside-header">
                <div>
                    <!-- 面包屑 -->
                    <el-breadcrumb separator=">">
                        <el-breadcrumb-item>账号管理</el-breadcrumb-item>
                        <el-breadcrumb-item class="breadcrumbColor">账号列表</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
            </el-header>
            <el-main>
                <div class="inside-main-box">
                    <el-row class="inside-main" style="height: 46px;">
                        <el-col :span="6" style="margin-left: 20px;">
                            <el-form-item label="用户名/昵称" size="small">
                                <el-input v-model="form.name" placeholder="请输入用户名或昵称" maxLength="10" clearable/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="margin-left: 20px;">
                            <el-button size="small" icon="search" class="sele-but" @click="getTableData()">查询</el-button>
                            <el-button size="small" icon="plus" class="add-but" @click="ruleForm.factory_id=factoryId>0?factoryId:null;centerDialogVisible = true;">新增</el-button>
                        </el-col>
                    </el-row>
                </div>
                <div style="height: 10px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
              </div>
                <div style="background: #fff;">
                    <el-table :data="tableData.rows" style="width: 100%;" height="460">
                        <el-table-column align="center" prop="序号" label="序号" width="60" type="index"/>
                        <el-table-column align="center" prop="usernumber" label="用户名" show-overflow-tooltip/>
                        <el-table-column align="center" prop="username" label="昵称" show-overflow-tooltip/>
                        <el-table-column align="center" prop="tel" label="手机号" show-overflow-tooltip/>
                      <el-table-column align="center" prop="status" label="状态" >
                          <template #default="item">
                             <span v-if="item.row.status" style="color:#42b983">启用</span>
                             <span v-else style="color:orangered">停用</span>
                          </template>
                      </el-table-column>
                      <el-table-column align="center" prop="factory_name" label="工厂" show-overflow-tooltip>
                        <template #default="item">
                           <span v-if="item.row.factory_id">{{tableData.factoryNames[item.row.factory_id]?.factory_name}}</span>
<!--                          <div v-for="fac in tableData.factorys" :key="fac.id">-->
<!--                            <span v-if="fac.id===item.row.factory_id">{{fac.factory_name}}</span>-->
<!--                          </div>-->
                        </template>
                      </el-table-column>
                     <el-table-column align="center" prop="角色" label="角色">
                        <template #default="item">
                           <span v-if="item.row.user_role">{{tableData.roleNames[item.row.user_role]?.role_name}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" prop="registration_time" width="180" label="创建时间" :formatter="function(row,column){
                          if(row.registration_time){
                            return $moment(row.registration_time).format('YYYY-MM-DD HH:mm:ss')
                          }else{
                            return ''
                          }
                        }" />
                  <el-table-column align="center" fixed="right" label="操作" width="240px">
                      <template #default="item">
                        <div v-if="item.row.uid>1">
                          <el-button link type="primary" icon="refresh" size="small" @click="reset(item.row)">重置</el-button>
                          <el-button link type="primary" icon="edit" size="small" @click="editDetail(item.row)">修改</el-button>
                          <el-button link type="danger" icon="video-pause" size="small" v-if="item.row.status" @click="changeStatus(item.row,0)">停用</el-button>
                          <el-button link type="success" icon="video-play" size="small" v-else @click="changeStatus(item.row,1)">启用</el-button>
                          <el-button link type="danger" icon="delete" size="small" @click="del(item.row)">删除</el-button>
                        </div>
                      </template>
    </el-table-column>
</el-table>
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
           size="small" layout="prev, pager, next, jumper,total"
           :total="queryInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
</div>
</el-main>
</el-container>
<!-- 新增弹窗 -->
<el-dialog v-model="centerDialogVisible" title="账户管理" width="40%">
    <div style="width:90%">
        <el-form ref="account" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="usernumber">
                <div>
                    <el-input v-model="ruleForm.usernumber" placeholder="请输入" maxLength="10" style="width:220px" autocomplete="off" clearable />
                </div>
                <div style="margin-left: 10px;">
                    <span style="font-size: 2px;color: #888;">支持中文、英文和数字</span>
                </div>
            </el-form-item>
            <el-form-item label="手机号" prop="tel">
                  <el-input v-model="ruleForm.tel" placeholder="请输入" maxLength="11" style="width:220px" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item label="昵称" prop="username">
              <div>
                <el-input v-model="ruleForm.username" placeholder="请输入" maxLength="16" autocomplete="off" style="width:220px" clearable />
              </div>
              <div style="margin-left: 10px;">
                <span style="font-size: 2px;color: #888;">最长16位</span>
              </div>
            </el-form-item>
            <el-form-item label="登录密码" v-show="!ruleForm.uid">
              <span style="font-size: 12px;color: #888;"> 默认为 123456</span>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="ruleForm.sex" placeholder="请输入" autocomplete="off" clearable >
                <el-option v-for="sex in sexes" :label="sex.label" :key="sex.value" :value="sex.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在工厂" prop="factory_id" v-if="factoryId>0">
              <el-input v-model="factory_name" disabled style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="工厂" prop="factory_id" v-else>
                <el-select v-model="ruleForm.factory_id" placeholder="请选择" clearable>
                    <el-option v-for="factory in tableData.factorys" :label="factory.factory_name" :key="factory.id" :value="factory.id" />
                </el-select>
            </el-form-item>
<!--            <el-form-item label="关联门禁">
                <el-select v-model="ruleForm.sal" placeholder="请选择" clearable>
                    <el-option v-for="(door,index) in doors" :label="door.label" :value="door.value" :key="door.value"/>
                </el-select>
            </el-form-item>-->
            <el-form-item label="角色" v-if="roleId==2 && ruleForm.user_role==2">
                <el-input disabled value="工厂管理员" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="角色" v-else>
                <el-select v-model="ruleForm.user_role" placeholder="请选择" clearable>
                    <el-option v-for="(role,index) in tableData.roles" :label="role.role_name" :value="role.id" :key="role.id"/>
                </el-select>
            </el-form-item>
        </el-form>
    </div>
    <template #footer>
                <span class="dialog-footer">
<!--                    <el-button class="sele-but" @click="centerDialogVisible = true">-->
<!--                        保存并添加下一个-->
<!--                    </el-button>-->
                    <el-button class="sele-but" @click="saveAccount()">保存</el-button>
                    <el-button class="empty-but" @click="revert()">取消</el-button>
                </span>
            </template>
</el-dialog>
</div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import md5 from 'js-md5';
import {userInfoByUsername,register,updateUserInfo,deleteUserInfo,queryAll,updateStatus} from "@/api/role"
import {getFactoryInfo,} from "@/api/factory"
import {ElMessage, ElMessageBox} from "element-plus";
const factoryId = localStorage.getItem("factoryId");
const factory_name = localStorage.getItem("factory_name");
const roleId = localStorage.getItem("roleId");
    // 新增弹窗 表单校验
    const ruleForm = reactive({
        usernumber: '',
        tel:'',
        username: '',
        user_role:'',
        factory_id:'',
        status:1,
        sal: '',
        sex: ''
    })
    const sexes = [{value:1,label:'男'},{value:0,label:'女'}]
    const doors = [{value:"1",label:'东1门'},{value:"2",label:'东2门'},{value:"3",label:'南1门'},{value:"4",label:'南2门'},
      {value:"5",label:'西1门'},{value:"6",label:'西2门'},{value:"7",label:'北1门'},{value:"8",label:'北2门'},]
    const validateTelephoneNumber =() =>{
      return (rule,value,callback)=>{
        if(!value){
          callback(new Error("手机号没填."))
        }else if(!/^1\d{10}$/.test(value)){
          callback(new Error("手机号码格式错误."))
        }else{
          callback();
        }
      }
    }
    const rules = {
        usernumber: [{
            required: true,
            message: "请输入用户名",
            trigger: "blur",
        }, {
            message: "请输入用户名",
            trigger: "blur",
        }],
      tel:[{required:true,validator:validateTelephoneNumber(),trigger:"blur"}],
      factory_id:[{required:true,message: "选择工厂",trigger:"blur"}],
    };
        // 新增弹窗
    const centerDialogVisible = ref(false)

    const name = 'transportIndex'
        // 时间
    const size = ref("default");
    const form = reactive({
        name: "",
    });
    const account = ref()
    const saveAccount = ()=>{
      account.value.validate(valid=> {
          if(valid){
            if (ruleForm.uid) {
              updateUserInfo(ruleForm).then(res=>{
                if(res&&res.code==200){
                  ElMessage.success("修改成功.");
                  revert();
                }else{
                  ElMessage.error(res.msg);
                }
              }).catch(e=>{
                console.log(e.response);
                ElMessage.error(e.msg);
              })
            }else{
              const pwd = md5("123456");
              ruleForm.userpwd = pwd;
              register(ruleForm).then(res=>{
                if(res&&res.code==200){
                  ElMessage.success("新增成功.");
                  revert();
                }else{
                  ElMessage.error(res.msg);
                }
              }).catch(e=>{
                console.log(e.response);
                ElMessage.error(e.msg);
              })
            }
        }
      });
    }
    const reset = (row)=>{
      if(roleId<row.user_role||!row.user_role){
        ElMessageBox.confirm("是否决定将密码重置为123456?").then(res=>{
          let password = md5("123456");
          let userinfo = {uid:row.uid,userpwd:password};
          updateUserInfo(userinfo).then(res=>{
            if(res.code==200){
              ElMessage.success("重置成功.");
              revert();
            }else{
              ElMessage.error("重置失败.");
            }
          })
        })
      }else{
        ElMessage.error("无法对同权限用户进行操作.");
      }
    }
    const editDetail = (row) =>{
      if(roleId<row.user_role||!row.user_role){
        ruleForm.uid = row.uid;
        ruleForm.usernumber = row.usernumber;
        ruleForm.tel = row.tel;
        ruleForm.status = row.status;
        ruleForm.username = row.username;
        ruleForm.user_role = row.user_role;
        ruleForm.factory_id = row.factory_id;
        ruleForm.sal = row.sal;
        ruleForm.sex = row.sex;
        centerDialogVisible.value=true;
      }else{
        ElMessage.error("无法对同权限用户进行操作.");
      }
    }

    const changeStatus = (row,status) =>{
      if(roleId<row.user_role||!row.user_role){
        ruleForm.uid = row.uid;
        ruleForm.status = status;
        updateStatus(ruleForm).then(res=>{
          if(res.code==200){
            ElMessage.success("修改成功.");
            revert();
          }else{
            ElMessage.error(res.msg);
          }
        })
      }else{
        ElMessage.error("无法对同权限用户进行操作.");
      }
    }
    // 表格假数据
    const tableData = reactive({
      rows:[],
      total:0,
      roles:[],
      roleNames:{},
      factorys:[],
      factoryNames:{},
    });
    const getTableData = ()=>{
      let obj = form.name?{username:form.name}:{pageSize:queryInfo.pagesize,pageNum:queryInfo.pagenum};
      userInfoByUsername(obj).then(res=>{
        tableData.rows = res.data.list;
        queryInfo.total=res.data.total;
      })
    }
    const getFactorys = ()=>{
      getFactoryInfo({pageSize:1000}).then(res=>{
        let factorys = [];
        res.data?.list.forEach(e=>{
          factorys.push(e);
            tableData.factoryNames[e.id]=e;
        })
        tableData.factorys = factorys;
      })
    }

    const getRoles = ()=>{
      queryAll({pageSize:1000}).then(res=>{
        let roles = [];
        res.data?.forEach(e=>{
          if(e.id>roleId){
            roles.push(e);
          }
          tableData.roleNames[e.id]=e;
        })
        tableData.roles = roles;
      })
    }
    const del = (row) =>{
      if(roleId<row.user_role||!row.user_role){
        ElMessageBox.confirm("确定要删除吗?")
            .then(() => {
              deleteUserInfo(row).then(res=>{
                if(res.code==200){
                  ElMessage.success("删除成功.");
                  revert();
                }else{
                  ElMessage.error(res.msg);
                }
              })
            })
      }else{
        ElMessage.error("无法对同权限用户进行操作.");
      }
    }
    const revert=()=>{
      ruleForm.uid = null;
      ruleForm.usernumber = '';
      ruleForm.tel = '';
      ruleForm.status = 1;
      ruleForm.username = '';
      ruleForm.user_role = '';
      ruleForm.factory_id = '';
      ruleForm.sal = '';
      ruleForm.sex = '';
      getTableData();
      account.value.clearValidate();
      centerDialogVisible.value=false;
    }
    onMounted(()=>{
      getTableData();
      getFactorys();
      getRoles();
    })
//分页
const queryInfo = reactive({
  pagenum:1,
  pagesize:10,
  total:0
})
const handleSizeChange = (val) => {
  queryInfo.pagesize = val
  getTableData()
}
//点击第几页
const handleCurrentChange = (val) => {
  queryInfo.pagenum = val
  getTableData()
}
</script>
<style scoped>
    /* 面包屑字体颜色更改 */
    .breadcrumbColor>>>.el-breadcrumb__inner {
        color: #000;
    }
    /* 内部header */
    .inside-header {
        height: 20px;
        display: flex;
        justify-content: left;
        align-items: flex-start;
      background:#f2f4f5
    }
    /* 空心按钮样式 */

    .empty-but {
        border: 1px solid #3780b9;
        color: #3780b9;
    }
    /* 实心按钮背景样式 */

    .sele-but {
        background: #3780b9;
        border: 0px;
        border-radius: 2px;
        color: white;
    }

    .add-but {
        background: #dde5fe;
        color: #3780b9;
    }
    /* 分页 */

    .demo-pagination-block {
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
</style>
